<template>
  <div class="course-book-detail" v-loading="loading">
    <div style="height: 40px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/courseBook' }"
          >考研书籍</el-breadcrumb-item
        >
        <el-breadcrumb-item>书籍详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="detail">
      <div class="detail-info">
        <p>
          课程名称：<span>{{ dataDetail.bookName }}</span>
        </p>
        <p>
          课程类型：<span>{{ dataDetail.courseCategory }}</span>
        </p>
        <p>课程封面：<span @click="look" class="click">点击查看</span></p>
        <el-image
          ref="previewImage"
          :src="dataDetail.cover"
          :preview-src-list="[dataDetail.cover]"
          style="display: none"
        ></el-image>
        <p>
          图书资料：<span class="click"
            ><a :href="dataDetail.bookFile" target="_blank">点击下载</a></span
          >
        </p>
        <p>
          收藏量：
          <span>{{ dataDetail.collectNum }}</span>
        </p>
        <p>
          发布日期：<span>{{ formatDate(dataDetail.createTime) }}</span>
        </p>
        <p>
          <el-link type="info" @click="dialogVisible = true"
            ><i class="el-icon-edit"></i>小评一下</el-link
          >
          <el-link type="info" class="collect">
            <span v-if="dataDetail.isCollect === 0" @click="collect"
              ><i class="el-icon-collection-tag"></i>点击收藏</span
            >
            <span v-else @click="cancelCollect"
              ><i class="el-icon-collection"></i>已收藏</span
            >
          </el-link>
        </p>
      </div>
    </div>
    <!-- 评论 -->
    <div class="detail-remark">
      <RemarkView
        :remarkList="remarkList"
        :total="total"
        :remarkListLoading="remarkListLoading"
      ></RemarkView>
      <el-pagination
        v-show="remarkList.length > 0"
        layout="prev, pager, next"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        :total="total"
        :page-count="7"
        style="text-align: right; margin-top: 20px"
      >
      </el-pagination>
    </div>
    <!-- dialog框（写评论） -->
    <el-dialog
      style="width: 60%; margin: 14vh auto 0"
      title="写短评"
      :center="true"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="remark"
        type="textarea"
        :autosize="{ minRows: 3, maxRows: 6 }"
        placeholder="请说出您的看法..."
      ></el-input>
      <div style="text-align: right">
        <el-button style="margin-top: 20px" @click="remark = ''"
          >清空</el-button
        >
        <el-button
          type="primary"
          style="margin-top: 20px"
          @click="writeRemark"
          :loading="remarkLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RemarkView from "@/components/RemarkView.vue";
import { getRemarkList } from "@/api/client/remark";
import { getCourseBookById } from "@/api/client/courseBook";
import { insertRemark } from "@/api/client/remark";
import { addCollect, delCollect } from "@/api/client/collect";
import userModule from "@/utils/userInfo";
export default {
  name: "CourseBookDetailView",
  props: ["id"],
  data() {
    return {
      dataDetail: {},
      loading: false,
      dialogVisible: false,
      remark: "",
      remarkLoading: false,
      page: 1,
      pageSize: 10,
      currentPage: 1,
      total: 0,
      remarkList: [],
      remarkListLoading: false,
    };
  },
  components: {
    RemarkView,
  },
  async created() {
    await this.getCourseBookById();
    await this.getRemarkList();
  },
  methods: {
    // 获取课程视频详情
    async getCourseBookById() {
      try {
        this.loading = true;
        const res = await getCourseBookById(this.id);
        this.dataDetail = res.data;
      } catch {
        this.$message.error("获取课程视频详情失败");
      } finally {
        this.loading = false;
      }
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 预览图片
    look() {
      this.$refs.previewImage.showViewer = true;
    },
    // 收藏
    async collect() {
      try {
        const res = await addCollect({
          type: "book",
          typeId: this.dataDetail.id,
          userId: userModule.getUser().id,
        });
        this.getCourseBookById();
      } catch {
        this.$message.error("收藏失败");
      }
    },
    // 取消收藏
    async cancelCollect() {
      try {
        const res = await delCollect({
          type: "book",
          typeId: this.dataDetail.id,
          userId: userModule.getUser().id,
        });
        this.getCourseBookById();
      } catch {
        this.$message.error("取消收藏失败");
      }
    },
    // 写小评
    async writeRemark() {
      if (this.remark.trim() === "") {
        this.$message.warning("评论不能为空");
        return;
      }
      // 转换格式
      this.remark = this.remark
        .replace(/\r\n/g, "<br/>")
        .replace(/\n/g, "<br/>")
        .replace(/\s/g, " ");
      try {
        this.remarkLoading = true;
        const res = await insertRemark({
          type: "book",
          courseId: this.id,
          content: this.remark,
        });
        this.dialogVisible = false;
        this.remark = "";
        this.getRemarkList();
      } finally {
        this.remarkLoading = false;
      }
    },
    // 获取评论
    async getRemarkList() {
      try {
        this.remarkListLoading = true;
        const res = await getRemarkList({
          type: "book",
          courseId: this.id,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.remarkList = res.data.records;
        this.total = res.data.total;
      } catch {
        this.$message.error("获取评论失败");
      } finally {
        this.remarkListLoading = false;
      }
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getRemarkList();
    },
  },
};
</script>

<style lang="less" scoped>
.course-book-detail {
  padding: 10px 60px;
  .detail {
    display: flex;
    .detail-info {
      width: 100%;
      margin-right: 20px;
      background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);
      box-shadow: 0 10px 14px rgba(00, 0, 0, 0.25);
      p {
        font-size: 17px;
        margin: 30px 40px;
        font-weight: 700;
        &:nth-of-type(1) {
          margin-top: 40px;
        }
        .click {
          color: #409eff;
          cursor: pointer;
          a {
            text-decoration: none;
            color: inherit;
          }
        }
        span {
          font-size: 16px;
        }
        .collect {
          margin-left: 20px;
          font-size: 14px;
        }
        /deep/.el-link--inner {
          font-weight: 700;
          transition: 0.3s;
          &:hover {
            font-size: 16px;
          }
        }
      }
    }
  }
}
</style>